package com.le.tester.delay;

import java.util.Objects;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

/**
 * 描述：继承自juc Delayed ,主要的实现层，会有一个延迟的时间和排队的方式，延迟时间和value作为初始化的值
 */
public class BaseDelayed<T> implements Delayed {

    private Long startTime;

    private T value;

    public BaseDelayed() {
    }

    public BaseDelayed(Long timeout, T value) {
        ////设置超时出队的时间点，也是一分钟一分钟慢慢的出队
        this.startTime = System.currentTimeMillis() + timeout * 1000L;
        this.value = value;
    }

    public long getStartTime() {
        return startTime;
    }

    public T getValue() {
        return value;
    }

    //返回剩下的延迟时间
    @Override
    public long getDelay(TimeUnit unit) {
        return unit.convert(this.getStartTime() - (System.currentTimeMillis()), TimeUnit.MILLISECONDS);
    }

    //比较的方式，排序之后，可以设置它的出队的先后顺序
    @Override
    public int compareTo(Delayed o) {
        //默认的字典排序
        if (o == this) {
            return 0;
        }
        if (o instanceof BaseDelayed) {
            BaseDelayed<?> otherRequest = (BaseDelayed<?>) o;
            return (int) (this.getStartTime() - otherRequest.getStartTime());
        }
        return 0;
    }

    @Override
    public String toString() {
        return "BaseDelayed{" +
                "startTime=" + startTime +
                ", Value=" + value +
                '}';
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        BaseDelayed<?> that = (BaseDelayed<?>) o;
        return startTime == that.startTime &&
                Objects.equals(value, that.value);
    }

    @Override
    public int hashCode() {
        return Objects.hash(startTime, value);
    }
}
